import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Brain, Clock, Trophy, Star, CheckCircle, X } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface AbstractReasoningTestProps {
  onComplete: (result: TestResult) => void;
}

interface AbstractProblem {
  id: number;
  type: 'analogy' | 'progression' | 'transformation' | 'classification' | 'spatial_relation' | 'logical_sequence';
  premise: AbstractElement[];
  question: AbstractElement[];
  options: AbstractElement[][];
  correct: number;
  difficulty: 'easy' | 'medium' | 'hard';
  description: string;
  rule: string;
}

interface AbstractElement {
  shapes: ShapeElement[];
  relation?: string;
}

interface ShapeElement {
  type: 'circle' | 'square' | 'triangle' | 'diamond' | 'cross' | 'star' | 'arrow' | 'line';
  position: { x: number; y: number };
  size: 'small' | 'medium' | 'large';
  color: 'black' | 'white' | 'gray';
  rotation?: number;
  style?: 'filled' | 'outline' | 'dashed';
  count?: number;
}

export function AbstractReasoningTest({ onComplete }: AbstractReasoningTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentProblem, setCurrentProblem] = useState(0);
  const [problems, setProblems] = useState<AbstractProblem[]>([]);
  const [responses, setResponses] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(900); // 15分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);

  const TOTAL_PROBLEMS = 12;

  // 通用的答案随机化函数
  const shuffleOptions = (options: AbstractElement[][], correctIndex: number = 0) => {
    // 确保options是valid的数组
    if (!Array.isArray(options) || options.length === 0) {
      return { shuffledOptions: options, newCorrectIndex: 0 };
    }
    
    const shuffled = [...options];
    const correctAnswer = shuffled[correctIndex];
    
    // Fisher-Yates洗牌算法
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    
    // 找到正确答案的新位置
    const newCorrectIndex = shuffled.findIndex(option => 
      JSON.stringify(option) === JSON.stringify(correctAnswer)
    );
    
    return { 
      shuffledOptions: shuffled, 
      newCorrectIndex: newCorrectIndex >= 0 ? newCorrectIndex : 0 
    };
  };

  // 渲染形状元素 - 显著增大图形尺寸
  const renderShape = (shape: ShapeElement, containerSize = 180) => {
    if (!shape) return null;

    const { type, position, size, color, rotation = 0, style = 'filled' } = shape;
    
    // 显著增大尺寸，让图形更清晰可见
    const actualSize = size === 'small' ? 32 : size === 'large' ? 64 : 48;
    
    const colorValue = {
      black: '#1f2937',
      white: '#ffffff',
      gray: '#6b7280'
    };

    const strokeColor = color === 'white' ? '#1f2937' : colorValue[color];
    const fillColor = style === 'outline' ? 'transparent' : colorValue[color];
    const strokeDasharray = style === 'dashed' ? '6,6' : undefined;

    const x = position.x * containerSize;
    const y = position.y * containerSize;

    const shapeProps = {
      fill: fillColor,
      stroke: strokeColor,
      strokeWidth: style === 'filled' ? 0 : 3,
      strokeDasharray,
      transform: `translate(${x}, ${y}) rotate(${rotation})`
    };

    const renderShapeElement = () => {
      switch (type) {
        case 'circle':
          return <circle cx={0} cy={0} r={actualSize/2} {...shapeProps} />;
        case 'square':
          return <rect x={-actualSize/2} y={-actualSize/2} width={actualSize} height={actualSize} {...shapeProps} />;
        case 'triangle':
          const h = actualSize * Math.sqrt(3) / 2;
          return <polygon points={`0,${-h/2} ${-actualSize/2},${h/2} ${actualSize/2},${h/2}`} {...shapeProps} />;
        case 'diamond':
          return <polygon points={`0,${-actualSize/2} ${actualSize/2},0 0,${actualSize/2} ${-actualSize/2},0`} {...shapeProps} />;
        case 'cross':
          const thickness = actualSize / 4;
          return (
            <g {...shapeProps}>
              <rect x={-thickness/2} y={-actualSize/2} width={thickness} height={actualSize} />
              <rect x={-actualSize/2} y={-thickness/2} width={actualSize} height={thickness} />
            </g>
          );
        case 'star':
          const points = Array.from({ length: 10 }, (_, i) => {
            const r = i % 2 === 0 ? actualSize/2 : actualSize/4;
            const angle = (i * Math.PI) / 5;
            return `${r * Math.cos(angle - Math.PI/2)},${r * Math.sin(angle - Math.PI/2)}`;
          }).join(' ');
          return <polygon points={points} {...shapeProps} />;
        case 'arrow':
          return (
            <g {...shapeProps}>
              <polygon points={`${-actualSize/3},${-actualSize/4} ${actualSize/3},0 ${-actualSize/3},${actualSize/4} ${-actualSize/6},0`} />
            </g>
          );
        case 'line':
          return <line x1={-actualSize/2} y1={0} x2={actualSize/2} y2={0} {...shapeProps} />;
        default:
          return <circle cx={0} cy={0} r={actualSize/2} {...shapeProps} />;
      }
    };

    return (
      <g key={`${type}-${position.x}-${position.y}`}>
        {Array.from({ length: shape.count || 1 }, (_, i) => (
          <g key={i} transform={`translate(${i * 6}, ${i * 6})`}>
            {renderShapeElement()}
          </g>
        ))}
      </g>
    );
  };

  // 渲染抽象元素 - 显著增大显示尺寸
  const renderAbstractElement = (element: AbstractElement, size = 160) => {
    if (!element || !element.shapes) return null;

    return (
      <div className="border-2 border-slate-300 rounded-lg bg-white flex items-center justify-center shadow-sm hover:shadow-md transition-shadow" 
           style={{ width: size, height: size }}>
        <svg width={size * 0.9} height={size * 0.9} viewBox={`0 0 ${size} ${size}`}>
          <g transform={`translate(${size/2}, ${size/2})`}>
            {element.shapes.map((shape, index) => renderShape(shape, size))}
          </g>
        </svg>
      </div>
    );
  };

  // 生成类比问题
  const generateAnalogyProblem = (id: number): AbstractProblem => {
    const shapeTypes = ['circle', 'square', 'triangle', 'diamond'] as const;
    const shape1 = shapeTypes[Math.floor(Math.random() * shapeTypes.length)];
    const shape2 = shapeTypes.filter(s => s !== shape1)[Math.floor(Math.random() * 3)];
    
    const premise = [
      { shapes: [{ type: shape1, position: { x: 0, y: 0 }, size: 'small', color: 'black' }] },
      { shapes: [{ type: shape1, position: { x: 0, y: 0 }, size: 'large', color: 'black' }] },
      { shapes: [{ type: shape2, position: { x: 0, y: 0 }, size: 'small', color: 'black' }] }
    ];

    const correctAnswer = { shapes: [{ type: shape2, position: { x: 0, y: 0 }, size: 'large', color: 'black' }] };
    const initialOptions = [
      correctAnswer,
      { shapes: [{ type: shape2, position: { x: 0, y: 0 }, size: 'medium', color: 'black' }] },
      { shapes: [{ type: shape1, position: { x: 0, y: 0 }, size: 'large', color: 'black' }] },
      { shapes: [{ type: shape2, position: { x: 0, y: 0 }, size: 'small', color: 'gray' }] }
    ];

    const { shuffledOptions, newCorrectIndex } = shuffleOptions(initialOptions, 0);

    return {
      id,
      type: 'analogy',
      premise,
      question: [correctAnswer],
      options: shuffledOptions.map(option => [option]),
      correct: newCorrectIndex,
      difficulty: 'easy',
      description: '类比推理：小图形变成大图形',
      rule: '大小变换：小 → 大'
    };
  };

  const generateProgressionProblem = (id: number): AbstractProblem => {
    const premise = [
      { shapes: [{ type: 'arrow', position: { x: 0, y: 0 }, size: 'medium', color: 'black', rotation: 0 }] },
      { shapes: [{ type: 'arrow', position: { x: 0, y: 0 }, size: 'medium', color: 'black', rotation: 60 }] },
      { shapes: [{ type: 'arrow', position: { x: 0, y: 0 }, size: 'medium', color: 'black', rotation: 120 }] }
    ];

    const correctAnswer = { shapes: [{ type: 'arrow', position: { x: 0, y: 0 }, size: 'medium', color: 'black', rotation: 180 }] };
    const initialOptions = [
      correctAnswer,
      { shapes: [{ type: 'arrow', position: { x: 0, y: 0 }, size: 'medium', color: 'black', rotation: 150 }] },
      { shapes: [{ type: 'arrow', position: { x: 0, y: 0 }, size: 'medium', color: 'black', rotation: 240 }] },
      { shapes: [{ type: 'arrow', position: { x: 0, y: 0 }, size: 'medium', color: 'black', rotation: 90 }] }
    ];

    const { shuffledOptions, newCorrectIndex } = shuffleOptions(initialOptions, 0);

    return {
      id,
      type: 'progression',
      premise,
      question: [correctAnswer],
      options: shuffledOptions.map(option => [option]),
      correct: newCorrectIndex,
      difficulty: 'medium',
      description: '序列递进：旋转规律',
      rule: '每次顺时针旋转60度'
    };
  };

  const generateTransformationProblem = (id: number): AbstractProblem => {
    const premise = [
      {
        shapes: [
          { type: 'triangle', position: { x: -0.2, y: 0 }, size: 'medium', color: 'black', rotation: 0 },
          { type: 'circle', position: { x: 0.2, y: 0 }, size: 'small', color: 'gray', style: 'outline' }
        ]
      }
    ];

    const correctAnswer = {
      shapes: [
        { type: 'triangle', position: { x: 0.2, y: 0 }, size: 'medium', color: 'black', rotation: 0 },
        { type: 'circle', position: { x: -0.2, y: 0 }, size: 'small', color: 'gray', style: 'outline' }
      ]
    };

    const initialOptions = [
      correctAnswer,
      { 
        shapes: [
          { type: 'triangle', position: { x: -0.2, y: 0 }, size: 'medium', color: 'gray', rotation: 0 },
          { type: 'circle', position: { x: 0.2, y: 0 }, size: 'small', color: 'black', style: 'filled' }
        ]
      },
      { 
        shapes: [
          { type: 'square', position: { x: 0.2, y: 0 }, size: 'medium', color: 'black', rotation: 0 },
          { type: 'diamond', position: { x: -0.2, y: 0 }, size: 'small', color: 'gray', style: 'outline' }
        ]
      },
      { 
        shapes: [
          { type: 'triangle', position: { x: -0.2, y: 0 }, size: 'large', color: 'black', rotation: 180 },
          { type: 'circle', position: { x: 0.2, y: 0 }, size: 'medium', color: 'gray', style: 'outline' }
        ]
      }
    ];

    const { shuffledOptions, newCorrectIndex } = shuffleOptions(initialOptions, 0);

    return {
      id,
      type: 'transformation',
      premise,
      question: [correctAnswer],
      options: shuffledOptions.map(option => [option]),
      correct: newCorrectIndex,
      difficulty: 'hard',
      description: '图形变换：镜像翻转',
      rule: '左右镜像变换'
    };
  };

  const generateClassificationProblem = (id: number): AbstractProblem => {
    const premise = [
      { shapes: [{ type: 'circle', position: { x: 0, y: 0 }, size: 'small', color: 'black' }] },
      { shapes: [{ type: 'circle', position: { x: 0, y: 0 }, size: 'medium', color: 'black' }] },
      { shapes: [{ type: 'circle', position: { x: 0, y: 0 }, size: 'large', color: 'black' }] }
    ];

    const correctAnswer = { shapes: [{ type: 'triangle', position: { x: 0, y: 0 }, size: 'medium', color: 'black' }] };
    const initialOptions = [
      correctAnswer,
      { shapes: [{ type: 'circle', position: { x: 0, y: 0 }, size: 'medium', color: 'gray' }] },
      { shapes: [{ type: 'circle', position: { x: 0, y: 0 }, size: 'small', color: 'white', style: 'outline' }] },
      { shapes: [{ type: 'circle', position: { x: 0, y: 0 }, size: 'medium', color: 'black' }] }
    ];

    const { shuffledOptions, newCorrectIndex } = shuffleOptions(initialOptions, 0);

    return {
      id,
      type: 'classification',
      premise,
      question: [correctAnswer],
      options: shuffledOptions.map(option => [option]),
      correct: newCorrectIndex,
      difficulty: 'easy',
      description: '分类归纳：找出不同类',
      rule: '前三个都是圆形，选择不同形状'
    };
  };

  const generateSpatialRelationProblem = (id: number): AbstractProblem => {
    const premise = [
      {
        shapes: [
          { type: 'square', position: { x: 0, y: -0.3 }, size: 'large', color: 'black' },
          { type: 'circle', position: { x: 0, y: 0.15 }, size: 'small', color: 'gray' }
        ]
      }
    ];

    const correctAnswer = {
      shapes: [
        { type: 'circle', position: { x: 0, y: -0.3 }, size: 'small', color: 'gray' },
        { type: 'square', position: { x: 0, y: 0.15 }, size: 'large', color: 'black' }
      ]
    };

    const initialOptions = [
      correctAnswer,
      { 
        shapes: [
          { type: 'square', position: { x: -0.3, y: 0 }, size: 'large', color: 'black' },
          { type: 'circle', position: { x: 0.15, y: 0 }, size: 'small', color: 'gray' }
        ]
      },
      { 
        shapes: [
          { type: 'triangle', position: { x: 0, y: -0.3 }, size: 'large', color: 'black' },
          { type: 'diamond', position: { x: 0, y: 0.15 }, size: 'small', color: 'gray' }
        ]
      },
      { 
        shapes: [
          { type: 'square', position: { x: 0, y: -0.3 }, size: 'small', color: 'black' },
          { type: 'circle', position: { x: 0, y: 0.15 }, size: 'large', color: 'gray' }
        ]
      }
    ];

    const { shuffledOptions, newCorrectIndex } = shuffleOptions(initialOptions, 0);

    return {
      id,
      type: 'spatial_relation',
      premise,
      question: [correctAnswer],
      options: shuffledOptions.map(option => [option]),
      correct: newCorrectIndex,
      difficulty: 'medium',
      description: '空间关系：位置和大小互换',
      rule: '上下位置交换 + 大小交换'
    };
  };

  // 生成抽象推理问题
  const generateProblems = (): AbstractProblem[] => {
    const problems: AbstractProblem[] = [];
    let problemId = 1;

    // 类比推理 (6道)
    for (let i = 0; i < 6; i++) {
      problems.push(generateAnalogyProblem(problemId++));
    }

    // 序列递进 (3道)
    for (let i = 0; i < 3; i++) {
      problems.push(generateProgressionProblem(problemId++));
    }

    // 变换规律 (2道)
    for (let i = 0; i < 2; i++) {
      problems.push(generateTransformationProblem(problemId++));
    }

    // 分类归纳 (1道)
    problems.push(generateClassificationProblem(problemId++));

    return problems.sort(() => Math.random() - 0.5);
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            handleComplete();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartTest = () => {
    const generatedProblems = generateProblems();
    setProblems(generatedProblems);
    setStage('test');
    setStartTime(Date.now());
  };

  const handleAnswer = (answerIndex: number) => {
    const problem = problems[currentProblem];
    const correct = answerIndex === problem.correct;
    
    setResponses(prev => [...prev, answerIndex]);
    
    if (correct) {
      setScore(prev => prev + 1);
    }
    
    setFeedbackCorrect(correct);
    setShowFeedback(true);
    
    setTimeout(() => {
      setShowFeedback(false);
      
      if (currentProblem < problems.length - 1) {
        setCurrentProblem(prev => prev + 1);
      } else {
        handleComplete();
      }
    }, 1500);
  };

  const handleComplete = () => {
    const totalProblems = problems.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalProblems) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'abstract-reasoning',
      score: accuracy,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalProblems,
        correctAnswers,
        accuracy,
        averageTimePerProblem: Math.round(timeUsed / totalProblems)
      }
    };

    setStage('results');
    onComplete(result);
  };

  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-4xl mx-auto"
      >
        <Card className="shadow-lg">
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <Brain className="w-8 h-8 text-purple-600" />
              抽象推理测试
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <p className="text-lg text-slate-600">
                测试您的抽象思维和逻辑推理能力
              </p>
              <div className="bg-purple-50 p-6 rounded-lg space-y-3">
                <h3 className="font-semibold text-purple-900">测试规则：</h3>
                <ul className="text-left space-y-2 text-purple-800">
                  <li>• 共12道抽象推理题目，时间限制15分钟</li>
                  <li>• 包含类比推理、序列递进、图形变换等类型</li>
                  <li>• 观察图形规律，从4个选项中选择正确答案</li>
                  <li>• 注意观察形状、大小、位置、数量等属性变化</li>
                  <li>• 每题会显示规律提示帮助理解</li>
                </ul>
              </div>
            </div>
            
            <div className="flex justify-center">
              <Button onClick={handleStartTest} size="lg" className="px-8 bg-purple-600 hover:bg-purple-700">
                开始测试
              </Button>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    const problem = problems[currentProblem];
    if (!problem) return null;

    return (
      <Card className="w-full max-w-6xl mx-auto shadow-lg">
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Brain className="w-6 h-6 text-purple-600" />
              抽象推理测试
            </CardTitle>
            <div className="flex items-center gap-4">
              <Badge variant="outline" className="flex items-center gap-1">
                <Clock className="w-4 h-4" />
                {formatTime(timeLeft)}
              </Badge>
              <Badge variant="secondary">
                {currentProblem + 1} / {TOTAL_PROBLEMS}
              </Badge>
            </div>
          </div>
          <Progress value={(currentProblem / TOTAL_PROBLEMS) * 100} className="mt-2" />
        </CardHeader>
        
        <CardContent className="space-y-8">
          <AnimatePresence mode="wait">
            <motion.div
              key={currentProblem}
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -20 }}
              transition={{ duration: 0.3 }}
              className="space-y-6"
            >
              {/* 问题描述 */}
              <div className="text-center space-y-2">
                <h3 className="text-lg font-semibold text-slate-700">{problem.description}</h3>
                <p className="text-sm text-purple-600 font-medium">规律：{problem.rule}</p>
                <Badge variant="outline" className={`${
                  problem.difficulty === 'easy' ? 'border-green-300 text-green-700' :
                  problem.difficulty === 'medium' ? 'border-yellow-300 text-yellow-700' :
                  'border-red-300 text-red-700'
                }`}>
                  {problem.difficulty === 'easy' ? '简单' : 
                   problem.difficulty === 'medium' ? '中等' : '困难'}
                </Badge>
              </div>

              {/* 题干展示 - 根据题目类型调整布局 */}
              <div className="bg-slate-50 rounded-lg p-6">
                {problem.type === 'analogy' && (
                  <div className="flex items-center justify-center gap-6">
                    <div className="flex items-center gap-4">
                      {renderAbstractElement(problem.premise[0], 140)}
                      <span className="text-2xl font-bold text-slate-600">:</span>
                      {renderAbstractElement(problem.premise[1], 140)}
                    </div>
                    <span className="text-3xl font-bold text-purple-600">::</span>
                    <div className="flex items-center gap-4">
                      {renderAbstractElement(problem.premise[2], 140)}
                      <span className="text-2xl font-bold text-slate-600">:</span>
                      <div className="w-[140px] h-[140px] border-2 border-dashed border-purple-400 rounded-lg flex items-center justify-center bg-purple-50">
                        <span className="text-4xl text-purple-400">?</span>
                      </div>
                    </div>
                  </div>
                )}

                {problem.type !== 'analogy' && (
                  <div className="flex items-center justify-center gap-4">
                    {problem.premise.map((element, index) => (
                      <motion.div
                        key={index}
                        initial={{ opacity: 0, scale: 0.8 }}
                        animate={{ opacity: 1, scale: 1 }}
                        transition={{ delay: index * 0.2 }}
                      >
                        {renderAbstractElement(element, 140)}
                      </motion.div>
                    ))}
                    <motion.div
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      transition={{ delay: 0.6 }}
                      className="flex items-center gap-2"
                    >
                      <span className="text-2xl text-slate-400">→</span>
                      <div className="w-[140px] h-[140px] border-2 border-dashed border-purple-400 rounded-lg flex items-center justify-center bg-purple-50">
                        <span className="text-4xl text-purple-400">?</span>
                      </div>
                    </motion.div>
                  </div>
                )}
              </div>

              {/* 选项 - 修复双框问题，增大图形尺寸 */}
              <div>
                <h4 className="text-md font-semibold text-slate-700 mb-4 text-center">选择正确答案：</h4>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-6 max-w-4xl mx-auto">
                  {problem.options.map((option, index) => (
                    <motion.div
                      key={index}
                      whileHover={{ scale: 1.05 }}
                      whileTap={{ scale: 0.95 }}
                    >
                      <Button
                        variant="outline"
                        onClick={() => handleAnswer(index)}
                        disabled={showFeedback}
                        className={`w-full h-48 p-4 transition-all duration-300 flex items-center justify-center ${
                          showFeedback && index === problem.correct 
                            ? 'bg-green-500 text-white border-green-500 hover:bg-green-600' 
                            : showFeedback && index !== problem.correct && responses[currentProblem] === index
                            ? 'bg-red-500 text-white border-red-500'
                            : 'hover:bg-purple-50 hover:border-purple-300'
                        }`}
                      >
                        {/* 显著增大选项图形尺寸，避免双框问题，添加null检查 */}
                        {option && option.length > 0 && option[0] && option[0].shapes ? (
                          <div className="w-[160px] h-[160px] flex items-center justify-center">
                            <svg width="150" height="150" viewBox="0 0 180 180">
                              <g transform="translate(90, 90)">
                                {option[0].shapes.map((shape, shapeIndex) => 
                                  shape ? renderShape(shape, 180) : null
                                )}
                              </g>
                            </svg>
                          </div>
                        ) : (
                          <div className="w-16 h-16 bg-slate-100 border border-slate-300 rounded flex items-center justify-center text-slate-400">
                            ?
                          </div>
                        )}
                      </Button>
                    </motion.div>
                  ))}
                </div>
              </div>

              {/* 反馈 */}
              <AnimatePresence>
                {showFeedback && (
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -20 }}
                    className={`p-4 rounded-lg flex items-center gap-3 ${
                      feedbackCorrect 
                        ? 'bg-green-100 text-green-800 border-2 border-green-200' 
                        : 'bg-red-100 text-red-800 border-2 border-red-200'
                    }`}
                  >
                    {feedbackCorrect ? (
                      <CheckCircle className="w-6 h-6" />
                    ) : (
                      <X className="w-6 h-6" />
                    )}
                    <div>
                      <div className="font-semibold">
                        {feedbackCorrect ? '正确！' : '错误'}
                      </div>
                      <div className="text-sm opacity-90">
                        {feedbackCorrect 
                          ? `很好！您掌握了${problem.rule}的规律。` 
                          : `正确答案是选项${problem.correct + 1}。规律是：${problem.rule}`
                        }
                      </div>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.div>
          </AnimatePresence>
        </CardContent>
      </Card>
    );
  }

  if (stage === 'results') {
    const accuracy = Math.round((score / TOTAL_PROBLEMS) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="shadow-lg">
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <Trophy className="w-8 h-8 text-yellow-600" />
              测试完成
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-purple-600">
                {accuracy}%
              </div>
              <p className="text-lg text-slate-600">
                您答对了 {score} / {TOTAL_PROBLEMS} 道题目
              </p>
              
              <div className="grid grid-cols-2 gap-4 mt-6">
                <div className="bg-purple-50 p-4 rounded-lg">
                  <div className="text-2xl font-bold text-purple-600">{score}</div>
                  <div className="text-sm text-purple-800">正确答案</div>
                </div>
                <div className="bg-blue-50 p-4 rounded-lg">
                  <div className="text-2xl font-bold text-blue-600">{formatTime(timeUsed)}</div>
                  <div className="text-sm text-blue-800">用时</div>
                </div>
              </div>
            </div>
            
            <div className="text-center">
              <p className="text-slate-600">
                抽象推理测试完成！您的抽象思维能力将帮助您在复杂问题分析和创新思考中发挥重要作用。
              </p>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}